package cn.edu.nju.software.cdiy.action.user.all;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.cdiy.bean.User;
import cn.edu.nju.software.cdiy.service.UserService;
import cn.edu.nju.software.cdiy.util.BusinessConstant;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements SessionAware {

	private Map<String, Object> session;
	private UserService userService;
	private User user;
	private String url;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getUrl() {
		return url;
	}

	@Override
	public void validate() {
		clearFieldErrors();
	}

	@Override
	public String input() throws Exception {
		if (session.containsKey(BusinessConstant.S_USER)) {
			return "loginAlready";
		}
		return INPUT;
	}

	@Override
	public String execute() throws Exception {
		if (session.containsKey(BusinessConstant.S_USER)) {
			return "loginAlready";
		}
		User newUser = userService.login(user);
		if(newUser == null) {
			addFieldError("login", "用户名或密码错误！");
			return ERROR;
		}
		session.put(BusinessConstant.S_USER, newUser);
		url = (String) session.get(BusinessConstant.S_USER_URL);
		return SUCCESS;
	}

}
